<template>
  <div class="upload-template">
    <a-modal
      v-model:open="props.open"
      title="导入数据"
      width="1200px"
      :footer="null"
      @cancel="onClose"
    >
      <div>
        <span style="font-size: 16px; color: #020817">1.下载批量导入模版</span>
      </div>
      <a-divider />
      <div class="p-5 pb-20 pt-0">
        <div class="mb-3">
          <span>根据提示信息完善表格内容</span>
        </div>
        <a-button
          type="primary"
          :icon="h(LinkOutlined)"
          @click="onTemplate"
          class="ml-2 mr-2"
        >
          导出模板
        </a-button>
      </div>
      <div>
        <span style="font-size: 16px; color: #020817">2.导入热源站户信息</span>
      </div>
      <a-divider />
      <div class="p-5 pb-20 pt-0">
        <div>
          <span style="color: #ff3860; font-size: 14px"
            >如果需要覆盖原有信息基础信息，请导出最新的热源基本信息，修改后导入。如导入新热源基础信息请忽略词条提示。
          </span>
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :multiple="true"
            :action="updateUrl"
            @change="handleChange"
            @drop="handleDrop"
            :headers="header"
            :beforeUpload="beforeUpload"
            accept=".xls,.xlsx,.et"
            class="mt-3"
          >
            <p class="ant-upload-drag-icon">
              <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">点击/拖拽文件上传</p>
            <p class="ant-upload-hint">
              请将填写好的文件拖拽至此，或点击选择文件
            </p>
            <p class="ant-upload-hint">
              (仅支持.xls、.xlsx、.et格式文件，文件大小限制2MB以内)
            </p>
          </a-upload-dragger>
        </div>
      </div>
      <div>
        <span style="font-size: 16px; color: #020817">3.上传附件</span>
      </div>
      <a-divider />
      <div class="p-5 pb-20 pt-0">
        <div class="mb-3">
          <span>点击选择文件(仅支持pdf/doc/docx/xls/xlsx/png/jpg格式文件)</span>
        </div>
        <a-upload
          v-model:file-list="fileLists"
          name="file"
          action="/api/ChargeSystem/upload/attachmentUpload"
          :headers="header"
          :beforeUpload="beforeUploadAttachment"
          accept=".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg"
          @change="handleChanges"
        >
          <a-button type="primary" :icon="h(UploadOutlined)" class="ml-2 mr-2">
            上传文件
          </a-button>
        </a-upload>
      </div>
      <!-- 提交按钮区域 -->
      <div class="flex items-center justify-end">
        <a-button type="primary" class="ml-2 mr-2" @click="handleSubmit">
          提交
        </a-button>
        <a-button> 取消 </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, h, ref } from 'vue';
import { useAccessStore } from '@vben/stores';
import {
  CloudDownloadOutlined,
  CloudUploadOutlined,
  LinkOutlined,
  UploadOutlined,
  InboxOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { getCustomerInformationImportConfirm } from '#/api/core/customerInformation';
const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  selectedType: {
    type: String,
    default: '热源', // 默认值可以根据需要设置
  },
});

const accessStore = useAccessStore();
const header = {
  Authorization: accessStore.accessToken || localStorage.getItem('token'),
};
const fileList = ref([]);
const fileLists = ref([]);
const emit = defineEmits(['onClose', 'refresh']);
const onClose = () => {
  emit('onClose');
};
const updateUrl = computed(() => {
  switch (props.selectedType) {
    case '热源':
      return '/api/ChargeSystem/import/verifyHeatSourceData';
    case '热站':
      return '/api/ChargeSystem/import/verifyHeatExchangeStationData';
    case '小区':
      return '/api/ChargeSystem/import/verifyVillageData';
    case '热用户':
      return '/api/ChargeSystem/import/importHouseDetailExcel';
  }
});
const beforeUpload = (file: File) => {
  const isXls = file.type === 'application/vnd.ms-excel';
  const isXlsx =
    file.type ===
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isEt = file.name.endsWith('.et');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isXls && !isXlsx && !isEt) {
    message.error('仅支持.xls、.xlsx、.et格式文件!');
  }
  if (!isLt2M) {
    message.error('文件大小限制2MB以内!');
  }
  return (isXls || isXlsx || isEt) && isLt2M;
};

const fileLocation = ref('');
const fileName = ref('');
const fileNumber = ref('');
const handleChange = (info: any) => {
  console.log(info);
  if (info.file.status === 'done') {
    if (info.file.response && info.file.response.code === 0) {
      message.success(`${info.file.name} 文件上传成功`);
      fileLocation.value = info.file.response.data.fileLocation;
      fileName.value = info.file.response.data.fileName;
      fileNumber.value = info.file.response.data.fileNumber;
    } else {
      message.error(
        `${info.file.name} 文件上传失败: ${info.file.response ? info.file.response.msg : '未知错误'}`,
      );
    }
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`);
  }
};
const attachmentLocation = ref('');
const handleChanges = (info: any) => {
  console.log(info);
  if (info.file.status === 'done') {
    if (info.file.response && info.file.response.code === 0) {
      message.success(`${info.file.name} 文件上传成功`);
      attachmentLocation.value = info.file.response.data.fileLocation;
    } else {
      message.error(
        `${info.file.name} 文件上传失败: ${info.file.response ? info.file.response.message : '未知错误'}`,
      );
    }
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`);
  }
};

const beforeUploadAttachment = (file: File) => {
  const isPdf = file.type === 'application/pdf';
  const isDoc = file.type === 'application/msword';
  const isDocx =
    file.type ===
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  const isXls = file.type === 'application/vnd.ms-excel';
  const isXlsx =
    file.type ===
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isPng = file.type === 'image/png';
  const isJpg = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  const isSupportedFormat =
    isPdf || isDoc || isDocx || isXls || isXlsx || isPng || isJpg;

  if (!isSupportedFormat) {
    message.error('仅支持pdf/doc/docx/xls/xlsx/png/jpg格式文件!');
  }
  if (!isLt2M) {
    message.error('文件大小限制2MB以内!');
  }
  return isSupportedFormat && isLt2M;
};

const onTemplate = () => {
  const templateMap = {
    热源: '/Execl/热源信息表.xls',
    热站: '/Execl/换热站信息表.xls',
    小区: '/Execl/小区信息表.xls',
    热用户: '/Execl/用户信息表.xls',
  };

  const templatePath =
    templateMap[props.selectedType as keyof typeof templateMap];
  if (templatePath) {
    const link = document.createElement('a');
    link.href = templatePath;
    link.download = templatePath.split('/').pop() || '';
    document.body.append(link);
    link.click();
    link.remove();
  }
};
const handleSubmit = () => {
  const data = {
    fileName: fileName.value,
    fileNumber: fileNumber.value,
    fileLocation: fileLocation.value,
    attachmentLocation: attachmentLocation.value,
    importType: props.selectedType,
  };
  getCustomerInformationImportConfirm(data).then((res: any) => {
    console.log(res);
    if (res.data.code == 200) {
      message.success('上传成功');
      onClose();
      emit('refresh');
    } else {
      message.error('上传失败');
    }
  });
};
</script>

<style lang="less" scoped>
.upload-template {
  :deep(.ant-upload-list) {
    margin-top: 12px;
  }
}
</style>
